package org.stayfool.auth.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.stayfool.auth.entity.auth.AppUser;
import org.stayfool.auth.service.AuthService;
import org.stayfool.auth.util.PasswordUtil;
import org.stayfool.auth.util.RequestUtil;

@Controller
public class IndexController {

	@Resource(name = "authService")
	private AuthService authService;

	@RequestMapping("/")
	public String index() {
		return "index";
	}

	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request) {
		return RequestUtil.getModelViewWithBasePath("login", request);
	}

	@RequestMapping(value = "/registerlogic", method = RequestMethod.POST)
	public String registerlogic(AppUser user) {
		if (user == null || StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			return "redirect:/register";
		}
		user.setSalt(PasswordUtil.generateSalt());
		user.setPassword(PasswordUtil.encryptPassword(user.getPassword(), user.getSalt()));

		authService.save(user);

		return "redirect:/login";
	}

	@RequestMapping("/register")
	public ModelAndView register(HttpServletRequest request) {
		return RequestUtil.getModelViewWithBasePath("register", request);
	}

}
